<template>
  <!-- 资产型号表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="12">
          <el-form-item label="量检具型号" prop="modelNo">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.modelNo"
              placeholder="请输入量检具型号"
              clearable
            />

            <span v-else>{{ formData.modelNo }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="量检具类型" prop="assetTypeId">
            <!-- <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetTypeId"
              placeholder="请输入量检具类型"
              clearable
            /> -->
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择量检具类型"
              v-model="formData.assetTypeId"
              :data="catalogList"
              node-key="id"
              :props="{
                label: 'assetTypeName',
                value: 'id',
                children: 'nodes',
              }"
              :render-after-expand="false"
              :check-strictly="true"
              style="width: 300px"
              clearable
            />
            <span v-else>{{ formData.assetTypeName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select
              v-model="formData.brandId"
              placeholder="请选择品牌"
              clearable
              v-if="!props.isReadonly"
              style="width: 300px"
              @change="changeBrand"
            >
              <el-option
                v-for="item in brandList"
                :key="`${item.id}`"
                :label="`${item.brandCode}-${item.brandName}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.brandName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制造商" prop="makerId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.makerName"
              placeholder="请输入制造商"
              clearable
              disabled
            />

            <span v-else
              >{{ formData.makerCode }}-{{ formData.makerName }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>
              <div style="width: 100%; word-break: break-all">
                {{ formData.remarks }}
              </div></span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>

            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createTime"
              placeholder="请输入创建时间"
              clearable
            />

            <span v-else>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建人" prop="createdUserId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserId"
              placeholder="请输入创建人"
              clearable
            />

            <span v-else>{{ formData.createdUserId }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建人" prop="createdUserName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserName"
              placeholder="请输入创建人"
              clearable
            />

            <span v-else>{{ formData.createdUserName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新时间" prop="lastUpdateTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              placeholder="请输入更新时间"
              clearable
            />

            <span v-else>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新人" prop="lastUpdatedUserId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserId"
              placeholder="请输入更新人"
              clearable
            />

            <span v-else>{{ formData.lastUpdatedUserId }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新人" prop="lastUpdatedUserName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserName"
              placeholder="请输入更新人"
              clearable
            />

            <span v-else>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMASSETMODELEDITE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  version: [],
  assetKind: [],
  assetTypeId: [
    { required: true, message: "请选择量检具类型", trigger: "change" },
  ],

  brandId: [{ required: true, message: "请选择品牌", trigger: "change" }],
  modelNo: [{ required: true, message: "请输入量检具型号", trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  organizationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeName: "",
  makerId: "",
  makerName: "",
  brandId: "",
  brandName: "",
  modelNo: "",
  remarks: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        makerCode,
        makerId,
        makerName,
        brandId,
        brandName,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        makerId,
        makerName,
        makerCode,
        brandId,
        brandName,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.brandId = "";
  formData.brandName = "";
  formData.modelNo = "";
  formData.remarks = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 资产型号保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/mtAssetmodel/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mtAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};

// 获取资产品牌数据
const brandList: any = ref([]);
const getBrandList = async () => {
  await request({
    url: "eam/eamassetbrand/getList",
    method: "post",
    data: {},
  }).then((res) => {
    brandList.value = res.data;
  });
};

// 选择品牌
const changeBrand = (e) => {
  formData.makerId = "";
  if (e) {
    brandList.value.forEach((element) => {
      if (e == element.id) {
        formData.makerId = element.makerId;

        formData.makerName = element.makerName;
      }
    });
  }
};
onMounted(() => {
  getCAtalogList();
  getBrandList();
}),
  // 组件销毁时调用
  onBeforeUnmount(() => {
    visibleDialog.value = false;
    emit("change-visible", false);
  });
</script>
